package com.jilian.mydemo.modul.order.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.NetworkUtil;
import com.jilian.mydemo.Constant;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.common.dto.PathDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.adapter.SignUpAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;

public class SingUpActivity extends BaseActivity implements CustomItemClickListener, SignUpAdapter.CloseListener,BDLocationListener {
    private SignUpAdapter adapter;
    private List<PathDto> datas;
    private RecyclerView recyclerView;
    private TextView tvOk;
    private GridLayoutManager gridLayoutManager;
    private OrderViewModel orderViewModel;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_singup;
    }

    @Override
    public void initView() {
        setNormalTitle("上门签到", v -> finish());
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, DisplayUtil.dip2px(this, 10));//下间距
        recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        tvOk = (TextView) findViewById(R.id.tv_ok);
        gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        datas = new ArrayList<>();
        PathDto dto = new PathDto();
        dto.setType(1);
        datas.add(dto);
        adapter = new SignUpAdapter(this, datas, this, this);
        recyclerView.setAdapter(adapter);
    }
    private OrderDto orderDto;
    @Override
    public void initData() {
        orderDto = (OrderDto) getIntent().getSerializableExtra("order");
    }

    @Override
    public void initListener() {
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<File> files = getFiles();
                visitSign(orderDto.getId(),currentLat+","+currentLon,files);
            }
        });
    }

    /**
     * 上门签到
     * @param id
     * @param location
     * @param files
     */
    private void visitSign(String id, String location, List<File> files) {
        showLoadingDialog();
        orderViewModel.visitSign(id,location,files);
        orderViewModel.getVisitSignliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if(dto.isSuccess()){
                    ToastUitl.showImageToastSuccess("提交成功");
                    finish();
                }
                else{
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    /**
     * 获取需要上传的文件
     * @return
     */
    private List<File> getFiles() {
        if(datas.size()==1&&datas.get(0).getType()==1){
            return null;
        }
        List<File> files = new ArrayList<>();
        for (int i = 0; i <datas.size() ; i++) {
            if(datas.get(i).getType()==2){
                files.add(new File(datas.get(i).getUrl()));
            }

        }
        return files;
    }

    @Override
    public void onItemClick(View view, int position) {
        if (datas.get(position).getType() == 2) {
            seePhoto();
        } else {
            showAddPhoto();
        }


    }

    @Override
    protected void onStart() {
        super.onStart();
        RxPermissions.getInstance(this).request(
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION//定位权限
        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //开启定位
                MyApplication.getInstance().mLocationClient.start();
                MyApplication.getInstance().mLocationClient.registerLocationListener(SingUpActivity.this);
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                ToastUitl.showImageToastTips("请打开定位权限");
            }
        });
    }

    /**
     * 查看图片
     */
    private void seePhoto() {

    }

    /**
     * 添加图片
     */
    private void showAddPhoto() {
        showSelectPhotoTypeDialog();
    }

    @Override
    public void close(int position) {
        datas.remove(position);
        if(datas.get(datas.size()-1).getType()==2){
            PathDto dto = new PathDto();
            dto.setType(1);
            datas.add(dto);
        }
        adapter = new SignUpAdapter(this, datas, this, this);
        recyclerView.setAdapter(adapter);
        initButtonEnable();
    }

    private void initButtonEnable() {
        if(datas.size()==1&&datas.get(0).getType()==1){
            tvOk.setEnabled(false);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_dark);
        }
        else{
            tvOk.setEnabled(true);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_normal);
        }
    }

    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(SingUpActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(SingUpActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(SingUpActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(SingUpActivity.this, FILE_PROVIDER, 10 - datas.size(), FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private String path;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    for (int i = 0; i < uriList.size(); i++) {
                        Uri uri = uriList.get(i);
                        path = SelectPhotoUtils.getRealPathFromURI(this, uri);
                        PathDto dto = new PathDto(path, 2);
                        datas.add(0, dto);
                        if(datas.size()==10){
                            datas.remove(datas.size()-1);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    initButtonEnable();
                    break;
                //相机
                case FROM_CAPTURE:
                    path = SelectPhotoUtils.capturePathResult();
                    PathDto dto = new PathDto(path, 2);
                    datas.add(0, dto);
                    if(datas.size()==10){
                        datas.remove(datas.size()-1);
                    }
                    adapter.notifyDataSetChanged();
                    initButtonEnable();
                    break;
            }

        }
    }
//    /**
//     * 打开位置设置
//     */
//    private void getLocationSetting() {
//        if (!NetworkUtil.isGpsOPen(this)) {
//            //  CcsApplication.getInstance().mLocationClient.stop();
//            //位置信息没有开启
//            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", BoundDetailActivity.this);
//            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//            //startActivity(in  tent);
//
//            return;
//        }
//    }
    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的维度
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            //获取定位地址
            currentLat = bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();
            MyApplication.getInstance().mLocationClient.stop();

        }
    }


}
